package org.example.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UtGenHelper {
    public void accept(String className, List<String> funcContents) throws IOException {
        String fileName = className + "Test";
        File file = new File(fileName);

        StringBuilder fileContentStringBuilder = new StringBuilder();
        fileContentStringBuilder.append(necessaryPackage);
        fileContentStringBuilder.append("@SpringBootTest\n");
        fileContentStringBuilder.append("public class ").append(fileName).append(" {\n");
        String targeObjectAutowired = makeTargeObjectAutowired(className);
        fileContentStringBuilder.append(targeObjectAutowired).append("\n");
        for (String funcContent : funcContents) {
            fileContentStringBuilder.append(makeTestFuncContent(funcContent)).append("\n");
        }

        fileContentStringBuilder.append("}");

        try (FileOutputStream fileOutputStream = new FileOutputStream(file + ".java")) {
            fileOutputStream.write(fileContentStringBuilder.toString().getBytes());
        }
    }

    private String makeTestFuncContent(String originFuncContent) {
        FuncVisitor funcVisitor = new FuncVisitor();
        FuncParseComponent funcParseComponent = funcVisitor.accept(originFuncContent);
        String testFuncContent = "";
        testFuncContent += "\t@Test\n\tpublic void test" + UtilsCollection.upperFirstChar(funcParseComponent.funcName)
                + "() {\n\t}";
        return testFuncContent;
    }

    private String makeTargeObjectAutowired(String targetClassName) {
        String autowiredContent = "";
        autowiredContent += "\t@Autowired\n\t" + "private " + targetClassName
                + " " + UtilsCollection.lowerFirstChar(targetClassName) + ";";
        return autowiredContent;
    }

    public static class FuncParseComponent {
        String funcName;
        List<String> argTypes = new ArrayList<>();
        List<String> argNames = new ArrayList<>();
        String returnType;

        @Override
        public String toString() {
            return "FuncParseComponent{" +
                    "funcName='" + funcName + '\'' +
                    ", argTypes=" + argTypes +
                    ", argNames=" + argNames +
                    ", returnType='" + returnType + '\'' +
                    '}';
        }
    }

    private final String necessaryPackage = "import org.junit.jupiter.api.Test;\n" +
            "import org.springframework.beans.factory.annotation.Autowired;\n" +
            "import org.springframework.boot.test.context.SpringBootTest;\n\n";
}
